from PIL import Image, ImageEnhance
from django.conf import settings

def get_image_obj(path):
	"""
	Returns a PIL Image object created from the image at the given path.
	"""
	return Image.open(path)

def resize_to_fit(input_image, max_size = settings.PHOTO_MAXSIZE):
	"""
	Resizes an image to fit in the max_size rectangle given as tuple: (x, y).
	"""
	input_image.thumbnail(max_size, Image.ANTIALIAS)
	return input_image

def square_bw_thumbnail(input_image):
	"""
	Returns a square black and white thumbnail of the given image.
	"""
	enhancer = ImageEnhance.Color(input_image)
	input_image = enhancer.enhance(0.0)
	# crop 15% off each side
	input_width, input_height = input_image.size
	width_crop = int(input_width / 100.0 * 15.0)
	height_crop = int(input_height / 100.0 * 15.0)
	thumbnail = input_image.crop(
		(
			width_crop,
			height_crop,
			input_width - width_crop,
			input_height - width_crop,
		)
	)
	width, height = thumbnail.size
	ratio = float(width) / float(height)
	if ratio >= 1.0:
		longer_side = width
		shorter_side = height
	else:
		longer_side = height
		shorter_side = width
	absolute_ratio = float(longer_side) / float(shorter_side)
	# calculate pre-crop size (the +2 is to give the resizer some breathing room,
	# it tends to screw up the edges)
	temp_size = int((settings.PHOTO_THUMBNAILSIZE + 2) * absolute_ratio)
	thumbnail.thumbnail((temp_size, temp_size), Image.ANTIALIAS)
	thumbnail = thumbnail.crop((0, 0, settings.PHOTO_THUMBNAILSIZE, settings.PHOTO_THUMBNAILSIZE))
	# add overlay for the round corners effect
	overlay = Image.open(settings.MEDIA_ROOT + "img/thumbnail_overlay.png")
	thumbnail.paste(overlay, (0, 0), overlay)
	return thumbnail
